<!-- eslint-disable no-irregular-whitespace -->
<template>
  <div id="manageQuestionView">
    <a-table
      :key="tableKey"
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.pageNum,
        total,
        pageSizeOptions: [10, 20, 50, 100],
        showPageSize: true,
      }"
      class="arco-table-cell"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
    >
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #tags="{ record }">
        <a-space>
          <a-tag
            v-for="(tag, index) of JSON.parse(record.tags)"
            :key="index"
            color="green"
            >{{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #judgeConfig="{ record }">
        <div>
          <span
            >时间限制：{{ JSON.parse(record.judgeConfig).timeLimit }}ms</span
          >
          <span
            >内存限制：{{ JSON.parse(record.judgeConfig).memoryLimit }}B</span
          >
          <span
            >堆栈限制：{{ JSON.parse(record.judgeConfig).stackLimit }}B</span
          >
        </div>
      </template>
      <template #status="{ record }">
        <a-space wrap>
          <a-tag :color="getStatusColor(record.status)" class="tag-list">
            {{ getStatusText(record.status) }}
          </a-tag>
        </a-space>
      </template>

      <template #optional="{ record }">
               
        <a-space>
                   
          <a-button type="primary" @click="doUpdate(record)"> 修改</a-button>  
          <a-button @click="handleClickWarning(record)" status="danger"
            >删除</a-button
          >
        </a-space>
             
      </template>
         
    </a-table>
     
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  Page_Question_,
  Question,
  QuestionControllerService,
} from "../../../generatedQue";
import message from "@arco-design/web-vue/es/message";
import * as querystring from "querystring";
import { useRouter } from "vue-router";
import { Modal } from "@arco-design/web-vue";
import { useStore } from "vuex";
const store = useStore();
const show = ref(true);
const tableRef = ref();
const tableKey = ref(0); // 新增 ref

const dataList = ref([] as Array<Question>);
const total = ref(0);
const searchParams = ref({
  pageSize: 10,
  pageNum: 1,
});
const loading = ref(true);
const onPageChange = async (page: number) => {
  console.log("onPageChange");
  console.log(page);
  tableKey.value++; // 修改 key 值触发重新渲染
  searchParams.value = {
    ...searchParams.value,
    pageNum: page,
  };
  console.log(searchParams.value);
  await loadData();
};
const getStatusText = (status: number) => {
  if (status === 0) {
    return "待审核";
  } else if (status === 1) {
    return "已通过";
  } else if (status === 2) {
    return "未通过";
  }
};
const getStatusColor = (status: number) => {
  if (status === 0) {
    return "orange";
  } else if (status === 1) {
    return "green";
  } else if (status === 2) {
    return "red";
  }
};
const onPageSizeChange = (pageSize: number) => {
  searchParams.value = {
    ...searchParams.value,
    pageSize: pageSize,
  };
};
const handleClickWarning = (question: Question) => {
  Modal.warning({
    title: "确定删除吗？",
    content: "点击确定按钮将删除该题目，其他地方取消删除",
    okText: "确定",
    cancelText: "取消",
    onOk: () => {
      doDelete(question);
    },
  });
};
const loadData = async () => {
  console.log(store.state.user.loginUser.userRole);
  console.log("++++++++++++++++++++", searchParams.value);
  const res = await QuestionControllerService.listQuestionByPageUsingPost("", {
    current: searchParams.value.pageNum,
    pageSize: searchParams.value.pageSize,
  });
  if (res.code === 0) {
    dataList.value = res.data.records;
    dataList.value.forEach((item) => {
      //将时间戳转换为格式YYYY-MM-DD HH:mm:ss
      if (item.createTime) {
        const date = new Date(item.createTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        item.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
    });
    total.value = res.data.total;
    loading.value = false;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 页面加载时，请求数据
 */
onMounted(async () => {
  await loadData();
});
const columns = [
  {
    title: "序号",
    slotName: "index",
    align: "center",
  },
  // 如果需要展示，则加入提交状态列
  ...(store.state.user.loginUser.userRole === "user"
    ? [
        {
          title: "提交状态",
          slotName: "status",
          align: "center",
        },
      ]
    : []),
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "标签",
    slotName: "tags",
  },

  {
    title: "提交数",
    dataIndex: "submitNum",
  },
  {
    title: "通过数",
    dataIndex: "acceptedNum",
  },
  {
    title: "判题配置",
    slotName: "judgeConfig",
  },
  ...(store.state.user.loginUser.userRole === "admin"
    ? [
        {
          title: "创建用户id",
          dataIndex: "userId",
          align: "center",
        },
      ]
    : []),
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];

const doDelete = async (question: Question) => {
  console.log(question);
  const res = await QuestionControllerService.deleteQuestionUsingPost(
    "",

    {
      id: question.id,
    }
  );
  if (res.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败");
  }
};

const router = useRouter();

const doUpdate = (question: Question) => {
  router.push({
    path: "/update/question",
    query: {
      id: question.id,
    },
  });
};
</script>

<style scoped>
#manageQuestionView {
}
.arco-table-cell {
  display: flex;
  align-items: center;
  justify-content: center !important;
  overflow: hidden !important;
}
</style>
